<template>
  <wave-flex-box style="margin-bottom: 50px">
    <el-input
        style="width: 50%;height: 50px"
        size="large"
        @change="searchChange"
        v-model="searchKeyword"
        placeholder="输入想要查找的内容吧"
    />
    <el-button type="primary" @click="doSearch" style="height: 50px" :loading="loading">
      搜索
    </el-button>
  </wave-flex-box>

  <el-tabs v-model="searchType" @tab-click="doTabClick" style="width: 100%;height: 100%;background: white">
    <el-tab-pane label="帖子" name="post">
      <div v-loading="loading">
        <post-search-card v-for="item in searchData" :key="item.id" :post="item"/>
        <el-empty v-if="!loading && searchData.length===0" description="没有查到任何数据，试试其它内容吧"/>
      </div>
    </el-tab-pane>
    <el-tab-pane label="用户" name="user">
      <div v-loading="loading">
        <user-search-card v-for="item in searchData" :key="item.id" :user="item"/>
        <el-empty v-if="!loading && searchData.length===0" description="没有查到任何数据，试试其它内容吧"/>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script setup>
import WaveFlexBox from "@/component/WaveFlexBox.vue";
import {ref, onMounted} from "vue"; // 添加 onMounted 导入
import {useRoute} from "vue-router";
import {centerSearch} from "@/views/system/search/js/SearchRequest.js";
import PostSearchCard from "@/views/system/search/PostSearchCard.vue";
import UserSearchCard from "@/views/system/search/UserSearchCard.vue";

const page = ref({
  pageNum: 1,
  pageSize: 10,
});
const route = useRoute();

const searchType = ref('post');
const searchKeyword = ref('');
const searchData = ref([]);
const loading = ref(false);

onMounted(() => {
  searchKeyword.value = route.params.keyword || '';
  doSearch();
});

const doSearch = async () => {
  // 如果关键词为空，不进行搜索
  if (!searchKeyword.value.trim()) {
    searchData.value = [];
    return;
  }
  loading.value = true;
  try {
    const res = await centerSearch({
      searchType: searchType.value,
      keyword: searchKeyword.value.trim(),
      ...page.value
    });
    if (res.success) {
      searchData.value = res.data?.records || [];
    } else {
      searchData.value = [];
    }
  } catch (error) {
    console.error('搜索请求错误:', error);
    searchData.value = [];
  } finally {
    loading.value = false;
  }
}

const doTabClick = (panel) => {
  searchType.value = panel.paneName;
  pageInit();
  doSearch();
}

const pageInit = () => {
  page.value.pageNum = 1;
  page.value.pageSize = 30;
}

const searchChange = (keyword) => {
  // 防抖处理，避免频繁请求
  clearTimeout(searchChange.timer);
  searchChange.timer = setTimeout(() => {
    pageInit();
    searchKeyword.value = keyword;
    doSearch();
  }, 500);
}
</script>

<style scoped>
</style>